package com.wisely.xxboot.web;

/**
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 *
 * @author shengping
 * @version 1.0
 * @date 2017/6/23
 */

import com.wisely.xxboot.domain.WiselyMessage;
import com.wisely.xxboot.domain.WiselyResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

@Controller
public class WsController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate; //1 通过SimpMessagingTemplate向浏览器发送消息

    @MessageMapping("/chat")
    public void handleChat(Principal principal, String msg) { //2 在springmvc中可以直接在参数中获得princopal中包含当前用户的信息
        if (principal.getName().equals("aping")) { //3 一段硬编码
            messagingTemplate.convertAndSendToUser("wisely", "/queue/notifications", principal.getName() + "-send:" + msg); //4 发送消息
        } else {
            messagingTemplate.convertAndSendToUser("aping", "/queue/notifications", principal.getName() + "-send:" + msg);
        }
    }

    @MessageMapping("/welcome") //1 相当于RequesMapping
    @SendTo("/topic/getResponse") //2 当有消息时，会对订阅了@sendto中的路径浏览器发送消息
    public WiselyResponse say(WiselyMessage message) throws Exception {
        System.out.println("等待3s");
        Thread.sleep(3000);
        return new WiselyResponse("welcome," + message.getName() + "!");
    }
}
